package com.fjw.service.impl;

import com.fjw.constant.IterationTimes;
import com.fjw.dao.RoleMapper;
import com.fjw.dao.UserMapper;
import com.fjw.pojo.User;
import com.fjw.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;

/**
 * @author fjw
 * @version 1.0
 * @date 2019/11/1 15:20
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public Integer register(User user ,Integer roleId) {
        //加密
        //在注册的时候进行加密
        String salt = UUID.randomUUID().toString();
        String s = new Sha256Hash(user.getPassword(), salt, IterationTimes.INTERATIONTIMES).toBase64();
        user.setPassword(s);
        user.setSalt(salt);
        Integer integer = userMapper.addUser(user);
        //给这个用户赋予角色
        roleMapper.addRole(user.getId(),roleId );


        return integer;
    }

    @Override
    public User login(String username) {
        return userMapper.findByUserName(username);
    }

    @Override
    public PageInfo<User> listByClazId(Integer clazId,Integer pageNum) {
        //处理分页
        PageHelper.startPage(pageNum,4 );
        List<User> userByClazId = userMapper.findUserByClazId(clazId);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (User user : userByClazId) {
            String format = simpleDateFormat.format(user.getRegistTime());
            user.setTime1(format);
        }
        return PageInfo.of(userByClazId);
    }
}
